package com.eascs.loan.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.StringUtil;
import com.eascs.crm.common.entity.CustomerBasicInfoEntity;
import com.eascs.crm.common.service.ICustomerInfoService;
import com.eascs.crm.common.vo.QueryCustomerVO;
import com.eascs.datalist.entity.O2oDataListEntity;
import com.eascs.file.FileService;
import com.eascs.loan.entity.O2oBankLoanData;
import com.eascs.loan.entity.O2oPaymentsPlan;
import com.eascs.loan.entity.O2oRepaymentEntity;
import com.eascs.loan.service.O2oPaymentsService;
import com.eascs.loan.service.impl.O2oLoanServiceImpl;
import com.eascs.loan.service.impl.O2oPaymentsServiceImpl;
import com.eascs.loan.vo.O2oRepaymentRecordFormEntity;
import com.eascs.loan.vo.O2oRepaymentRecordVo;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.vo.ModelResult;

/**
 * @ClassName: O2oPaymentsRestController
 * @Description: 还款管理
 * @author 张庆奇
 * @date 2016年6月16日 下午5:53:45
 * @version V1.0
 */
@RestController
@RequestMapping("/paymentsRest")
public class O2oPaymentsRestController extends BaseRestController {

	@Inject
	O2oPaymentsService o2oPaymentsService;
	@Autowired
	private O2oLoanapplyService loanService;
	@Reference
	private ICustomerInfoService customerInfoService;
	@Autowired
	private FileService fileService;
	@Autowired
	O2oPaymentsServiceImpl o2oPaymentsServiceImpl;
	@Autowired
	O2oLoanServiceImpl o2oLoanServiceImpl;
	

	private static Logger log = LoggerFactory.getLogger(O2oPaymentsRestController.class);

	/**
	 * @Title: savePayments
	 * @Description:保存
	 * @author 张庆奇
	 * @param payments
	 * @return
	 * @return String
	 * @throws @date
	 *             2016年6月17日 上午9:34:06
	 */
	@RequestMapping("/savePayments")
	public BaseRestResult<?> savePayments(O2oPaymentsPlan payments) {
		BaseRestResult<?> result = null;
		String billCode = payments.getBillCode();
		String name = payments.getName();
		String idNumber = payments.getIdNumber();
		if (StringUtil.isEmpty(billCode) && StringUtil.isEmpty(name) && StringUtil.isEmpty(idNumber)) {
			result = BaseRestResult.warn("贷款单号、借款人姓名、借款人证件号三者必须有一个");
			return result;
		}

		// 如果单款单号不为空，则查看是否存在，如果存在，则取出借款姓名、证件号码
		if (StringUtil.isNotBlank(billCode)) {
			O2oLoanapplyEntity loanapply = loanService.fingByBillCode(billCode);
			if (loanapply == null) {
				result = BaseRestResult.warn("贷款单号不存在");
				return result;

			} else {
				QueryCustomerVO vo = new QueryCustomerVO();
				vo.setCustomer_id(loanapply.getLoanId());
				CustomerBasicInfoEntity info = customerInfoService.getCustomerBasicInfoEntity(vo);
				if (info != null) {
					name = info.getCustomerName();
					idNumber = info.getIdNumber();
				} else {
					result = BaseRestResult.warn("借款人信息不存在");
					return result;

				}

			}
		}

		// 如果单款单号为空并且贷款证件不为空，则根据借款人证件、借款状态为申报完成：SF、已放款/审批通过：O
		if (StringUtil.isNull(billCode) && StringUtil.isNotBlank(idNumber)) {
			QueryCustomerVO vo = new QueryCustomerVO();
			vo.setId_number(idNumber);
			CustomerBasicInfoEntity info = customerInfoService.getCustomerBasicInfoEntity(vo);
			if (info == null) {
				result = BaseRestResult.warn("没有找到借款人证件号为：" + idNumber + "该用户的信息");
				return result;
			} else {
				List<O2oLoanapplyEntity> list = o2oPaymentsService.findO2oLoanapplyEntity(info.getCustomerId());
				if (list != null) {
					if (list.size() == 0) {
						result = BaseRestResult.warn("没有找到借款人证件号为" + idNumber + "该用户的申报完成或者放款完成的贷款申请信息");
						return result;
					} else if (list.size() > 1) {
						result = BaseRestResult.warn("[证件号为:" + idNumber + "的借款用户，需要手工录入相关信息，请在系统中查询贷款单号后，手动添加]");
						return result;
					} else if (list.size() == 1) {

						billCode = list.get(0).getBillCode();
						name = info.getCustomerName();
					}

				}

			}

		}

		// 如果单款单号为空并且借款姓名不为空，身份证信息为空，则根据借款姓名、借款状态为申报完成：SF、已放款/审批通过：O查询billCode
		if (StringUtil.isNull(billCode) && StringUtil.isNull(idNumber) && StringUtil.isNotBlank(name)) {

			List<O2oLoanapplyEntity> list = o2oPaymentsService.findO2oLoanapplyEntityByName(name);
			if (list != null) {
				if (list.size() == 0) {
					result = BaseRestResult.warn("没有找到姓名为" + name + "该用户的申报完成或者放款完成的贷款申请信息");
					return result;
				} else if (list.size() > 1) {
					result = BaseRestResult.warn("[姓名:" + name + "的借款用户，需要手工录入相关信息，请在系统中查询贷款单号后，手动添加]");
					return result;
				} else if (list.size() == 1) {

					billCode = list.get(0).getBillCode();
					if (StringUtil.isNotBlank(list.get(0).getLoanId())) {
						QueryCustomerVO vo = new QueryCustomerVO();
						vo.setCustomer_id(list.get(0).getLoanId());
						CustomerBasicInfoEntity info = customerInfoService.getCustomerBasicInfoEntity(vo);
						idNumber = info.getIdNumber();
					}

				}
			}
		}
		payments.setBillCode(billCode);
		payments.setName(name);
		payments.setIdNumber(idNumber);
		payments.setRepaymentStatus("HKZ");
		String paymentsId = o2oPaymentsService.savePayments(payments);
		result = BaseRestResult.warn("添加成功").andRedirect("/payments/payments_list?payments_id" + paymentsId);
		return result;
	}

	
	/**
	 * @Title: dowanload
	 * @Description: 还款计划下载
	 * @author 张庆奇
	 * @param httpServletResponse
	 * @param request
	 * @param billCode
	 * @return
	 * @return BaseRestResult<String>
	 * @throws
	 * @date 2017年8月23日 上午10:43:16
	 */
	@RequestMapping("/download")
	public BaseRestResult<String> download(HttpServletResponse httpServletResponse, HttpServletRequest request,String billCode) {
		BaseRestResult<String> result = null;
		O2oBankLoanData bankLoan=o2oLoanServiceImpl.queryBillCode(billCode);
		String url="payments_plan.xls" ;//下载模板的路径
		if(bankLoan!=null&&StringUtil.isNotBlank(bankLoan.getLoanBank())){
			if(bankLoan.getLoanBank().equals("JCB")){
				url="JCB.xls" ;
			}else if(bankLoan.getLoanBank().equals("GACZ")){
				url="GACZ.xls" ;
			}else if(bankLoan.getLoanBank().equals("ZZB")){
				url="ZZB.xls" ;
			}else if(bankLoan.getLoanBank().equals("SPDBGZ")){
				url="SPDBGZ.xls" ;
			}
			
			
		}
		String file = O2oPaymentsRestController.class.getResource("/excelTemplate/"+url).getPath();

		OutputStream os = null;
		try {
			String outfile = "还款计划.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(file);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}

		return result;
	}

	/**
	 * @Title: delPayments
	 * @Description: 删除还款计划信息
	 * @author 张庆奇
	 * @param payments_id
	 * @return
	 * @return BaseRestResult<?>
	 * @throws @date
	 *             2016年6月21日 下午2:28:13
	 */
	@RequestMapping("/delPayments")
	public BaseRestResult<?> delPayments(String payments_id, String bill_code) {
		boolean flag = false;
		BaseRestResult<?> result = null;
		if (payments_id != null) {
			String sqlRUN = "select count(*) from o2o_repayment_record orr where orr.is_delete='N' and orr.bill_status in ('RUN','CLO') and orr.repayment_no = ?";
			String sqlNEW = "select count(*) from o2o_repayment_record orr where orr.is_delete='N' and orr.bill_status in ('NEW') and orr.repayment_no = ?";
			int countNew = o2oPaymentsServiceImpl.checkDeleteSpan(sqlNEW, payments_id);
			int countRUN = o2oPaymentsServiceImpl.checkDeleteSpan(sqlRUN, payments_id);
			if (countRUN > 0) {
				return BaseRestResult.warn("该还款计划已经有还款流程或记录不能删除");
			}
			if (countNew > 0) {
				return BaseRestResult.warn("该还款计划已经有新建的还款记录不能删除，须先删除还款记录");
			}
			flag = o2oPaymentsService.delPayments(payments_id);
		}
		if (flag == true) {
			result = BaseRestResult.info("删除成功").andRefresh();
		} else if (flag == false) {
			result = BaseRestResult.error("删除失败").andRefresh();
		}
		return result;
	}

	/**
	 * 银行放款 ---删除动态表单
	 * 
	 * @Title: delPayments
	 * @Description: 删除还款计划信息
	 * @param payments_id
	 * @return
	 * @return BaseRestResult<?>
	 * @throws @date
	 *             2016年6月21日 下午2:28:13
	 */
	@RequestMapping("/paymentsDel")
	public BaseRestResult<String> paymentDel(String payments_id) {
		boolean flag = false;
		if (payments_id != null) {
			flag = o2oPaymentsService.delPayments(payments_id);
		}
		BaseRestResult<String> result = null;
		if (flag == true) {
			result = BaseRestResult.buildClosestReloadResult();
		} else if (flag == false) {
			result = BaseRestResult.error("删除失败");
		}
		return result;
	}

	/**
	 * @param loanapplyNo
	 * @description
	 * 				<p>
	 *              还款表单填写
	 *              </p>
	 * @author CXW
	 * @date 2016年8月26日 下午5:04:44
	 * @version V1.0
	 * @return BaseRestResult<String>
	 */
	@RequestMapping("/repayment")
	public BaseRestResult<String> repaymentView(String paymentsId, String billCode) {
		ViewContext.put("paymentsId", paymentsId);
		ViewContext.put("billCode", billCode);
		O2oPaymentsPlan o2oPaymentsPlan = o2oPaymentsServiceImpl.findByIdEntity(paymentsId);
		//O2oRepaymentEntity o2oRepaymentEntity = o2oPaymentsServiceImpl.findEntityByRepaymentNo(paymentsId);
		//查询是否存在流程中的单
		String o2o_bank_run_sql = "select count(1) from o2o_repayment_record orr where orr.is_delete='N' and orr.bill_status = 'RUN' and orr.repayment_no = ?";
		int o2o_bank_run = o2oPaymentsServiceImpl.checkDeleteSpan(o2o_bank_run_sql, paymentsId);
		//查询是否存在新建的单
		String o2o_bank_new_sql = "select count(1) from o2o_repayment_record orr where orr.is_delete='N' and orr.bill_status = 'NEW' and orr.repayment_no = ?";
		int o2o_bank_new = o2oPaymentsServiceImpl.checkDeleteSpan(o2o_bank_new_sql, paymentsId);
		//查询已还款利息金额
		String repayment_interest = o2oPaymentsServiceImpl.findBigDecimal(repayment_interest_sql, paymentsId);
		//查询已还款本金金额
		String repayment_penalty = o2oPaymentsServiceImpl.findBigDecimal(repayment_penalty_sql, paymentsId);
		
		if (o2o_bank_run > 0) {
			return BaseRestResult.warn("流程正在进行中，不能发起还款");
		}
		
		if (o2o_bank_new > 0) {
			return BaseRestResult.warn("已有新建的流程，不能重复发起还款");
		}
		
		int principal = o2oPaymentsPlan.getPayPrincipal().subtract(new BigDecimal(repayment_penalty)).compareTo(BigDecimal.ZERO);
		int interest = o2oPaymentsPlan.getPayInterest().subtract(new BigDecimal(repayment_interest)).compareTo(BigDecimal.ZERO);
		if (principal == 0 && interest == 0) {
			return BaseRestResult.warn("本期已结清，不能再发起还款");
		}
		O2oRepaymentRecordVo entityResouce = new O2oRepaymentRecordVo();
		
		entityResouce.setBillCode(billCode);
		entityResouce.setUserName(o2oPaymentsPlan.getName());
		entityResouce.setPeriods((int) o2oPaymentsPlan.getPeriods());
		entityResouce.setPayPrincipal(o2oPaymentsPlan.getPayPrincipal().toString());
		entityResouce.setPayInterest(o2oPaymentsPlan.getPayInterest().toString());
		entityResouce.setWeiPayPrincipal(o2oPaymentsPlan.getPayPrincipal().subtract(new BigDecimal(repayment_penalty)).toString());
		entityResouce.setWeiPayInterest(o2oPaymentsPlan.getPayInterest().subtract(new BigDecimal(repayment_interest)).toString());
		
		O2oLoanapplyEntity loanEntity = loanService.fingByBillCode(billCode);
		if (null == loanEntity) {
			return BaseRestResult.warn("贷款单号异常，请检查数据是否正常");
		}
		O2oRepaymentEntity o2oRepaymentEntity = new O2oRepaymentEntity();
		o2oRepaymentEntity.setLoanapply_no(loanEntity.getLoanapplyNo());
		o2oRepaymentEntity.setBill_code(billCode);
		o2oRepaymentEntity.setPeriods((int)o2oPaymentsPlan.getPeriods());
		o2oRepaymentEntity.setRepayment_no(o2oPaymentsPlan.getPaymentsId());
		o2oRepaymentEntity.setUpdate_time(new Date());
		o2oRepaymentEntity.setBill_status(StatusContexts.O2O_NEW);
		o2oPaymentsService.insertO2oRepaymentEntity(o2oRepaymentEntity);
		entityResouce.setPaymentsId(o2oRepaymentEntity.getId());
		ViewContext.put("entity", entityResouce);
		return HtmlRestResult.popHtmlFragment("bank/repayment");
	}

	// @RequestMapping("/upRepayment")
	public BaseRestResult<String> repaymentUp(O2oRepaymentRecordFormEntity entity) {
		if (null == entity.getHuanPayPrincipal()) {
			return BaseRestResult.warn("请输入本次还本金");
		}
		if (null == entity.getHuanPayInterest()) {
			return BaseRestResult.warn("请输入本次还利息");
		}
		if (null == entity.getRepaymentPenalty()) {
			return BaseRestResult.warn("请输入罚息");
		}
		if (null == entity.getActualRepaymentDate()) {
			return BaseRestResult.warn("请选择实际还款时间");
		}
		return BaseRestResult.warn("贷款单号异常，请检查数据是否正常");
	}

	@RequestMapping("/updateRe")
	public BaseRestResult<String> repaymentUpdate(O2oRepaymentRecordVo entity) {
		if (null == entity.getHuanPayPrincipal()) {
			return BaseRestResult.warn("请输入本次还本金");
		}
		if (null == entity.getHuanPayInterest()) {
			return BaseRestResult.warn("请输入本次还利息");
		}
		if (null == entity.getRepaymentPenalty()) {
			return BaseRestResult.warn("请输入罚息");
		}
		if (null == entity.getActualRepaymentDate()) {
			return BaseRestResult.warn("请选择实际还款时间");
		}
		O2oRepaymentEntity o2oRepaymentEntityE = o2oPaymentsServiceImpl.findEntityById(entity.getPaymentsId());
		O2oPaymentsPlan o2oPaymentsPlan = o2oPaymentsServiceImpl.findByIdEntity(o2oRepaymentEntityE.getRepayment_no());
		//查询已还款利息金额
		String repayment_interest = o2oPaymentsServiceImpl.findBigDecimal(repayment_interest_sql, o2oRepaymentEntityE.getRepayment_no());
		//查询已还款本金金额
		String repayment_penalty = o2oPaymentsServiceImpl.findBigDecimal(repayment_penalty_sql, o2oRepaymentEntityE.getRepayment_no());
		BigDecimal principal = o2oPaymentsPlan.getPayPrincipal().subtract( new BigDecimal(repayment_penalty));
		BigDecimal interest = o2oPaymentsPlan.getPayInterest().subtract( new BigDecimal(repayment_interest));
		if (entity.getHuanPayPrincipal().compareTo(principal) > 0) {
			return BaseRestResult.warn("输入本次还本金不能大于剩余未还本金");
		}
		if (entity.getHuanPayInterest().compareTo(interest) > 0) {
			return BaseRestResult.warn("输入本次还利息不能大于剩余未还利息");
		}

		O2oLoanapplyEntity loanEntity = loanService.fingByBillCode(entity.getBillCode());
		if (null == loanEntity) {
			return BaseRestResult.warn("贷款单号异常，请检查数据是否正常");
		}
		if (isUploadFile(loanEntity.getLoanapplyNo(), entity.getPaymentsId())) {
			O2oRepaymentEntity o2oRepaymentEntity = new O2oRepaymentEntity();
			o2oRepaymentEntity.setId(entity.getPaymentsId());
			o2oRepaymentEntity.setLoanapply_no(loanEntity.getLoanapplyNo());
			o2oRepaymentEntity.setBill_code(entity.getBillCode());
			o2oRepaymentEntity.setPeriods(entity.getPeriods());
			o2oRepaymentEntity.setRepayment_no(o2oRepaymentEntityE.getRepayment_no());
			o2oRepaymentEntity.setActual_repayment_date(entity.getActualRepaymentDate());
			o2oRepaymentEntity.setRepayment_principal(entity.getHuanPayPrincipal());
			o2oRepaymentEntity.setRepayment_interest(entity.getHuanPayInterest());
			o2oRepaymentEntity.setRepayment_penalty(entity.getRepaymentPenalty());
			o2oRepaymentEntity.setUpdate_time(new Date());
			o2oRepaymentEntity.setBill_status(StatusContexts.O2O_NEW);
			int i = o2oPaymentsServiceImpl.updateO2oRepaymentEntity(o2oRepaymentEntity);
			if (i > 0) {
				return BaseRestResult.info("保存成功").andRefresh();
			} else {
				return BaseRestResult.warn("保存失败，请稍后重试");
			}
		} else {
			return BaseRestResult.warn("请上传还款凭证");
		}
	}

	@RequestMapping("/start")
	public BaseRestResult<String> startUp(String id) {
		O2oRepaymentEntity o2oRepaymentEntity = o2oPaymentsServiceImpl.findEntityById(id);
		if (StatusContexts.WFTYPE_STATUS_CLO.equals(o2oRepaymentEntity.getBill_status())) {
			return BaseRestResult.warn("流程已走完，不能重复发起");
		}
		boolean principal = null == o2oRepaymentEntity.getRepayment_principal();
		boolean interest = null == o2oRepaymentEntity.getRepayment_interest();
		boolean penalty = null == o2oRepaymentEntity.getRepayment_penalty();
		boolean repayment_date = null == o2oRepaymentEntity.getActual_repayment_date();
		if (principal || interest || penalty || repayment_date) {
			return BaseRestResult.warn("请完善还款记录信息，再发起流程");
		}
		ModelResult<Boolean> model = o2oPaymentsServiceImpl.startPayBack(o2oRepaymentEntity);
		if (model.isSuccess()) {
			String sql = "UPDATE O2O_REPAYMENT_RECORD ORR SET ORR.BILL_STATUS=? WHERE ORR.ID=?";
			o2oPaymentsServiceImpl.updateBySQL(sql, StatusContexts.O2O_BANK_RUN, id);
			return BaseRestResult.info("发起成功").andRefresh();
		} else {
			log.error("发起还款流程失败，失败原因：{}", model.getDetailStack());
			return BaseRestResult.warn(model.getErrMsg());
		}
	}

	/**
	 * @Description:
	 * 				<p>
	 *               上传贷款凭证
	 *               </p>
	 * @author CXW
	 * @date 2016年8月30日 上午11:02:56
	 * @version V1.0
	 * @param
	 * @return BaseRestResult<String>
	 */
	@RequestMapping(value = "/repayfile")
	public BaseRestResult<String> loanUpload(@RequestParam MultipartFile file, String loanapplyNo, String datalist, String paymentsId) {
		fileService.upload(file, datalist, loanapplyNo, paymentsId);
		return BaseRestResult.buildClosestReloadResult();
	}

	public boolean isUploadFile(String loanapplyNo, String paymentsId) {
		O2oDataListEntity data = fileService.getByBillCodeDataList(loanapplyNo, paymentsId);
		if (null == data) {
			return false;
		} else {
			return true;
		}
	}

	@Autowired
	private BaseUtils baseUtils;
	/**
	 * 查询已还款利息金额SQL
	 */
	String repayment_interest_sql = "select ifnull(sum(orr.repayment_interest),0) repayment_interest from o2o_repayment_record orr where orr.is_delete='N' and orr.repayment_no = ?";
	/**
	 * 查询已还款本金金额SQL
	 */
	String repayment_penalty_sql = "select ifnull(sum(orr.repayment_principal),0) repayment_principal from o2o_repayment_record orr where orr.is_delete='N' and orr.repayment_no = ?";
	
	@RequestMapping("/repayView")
	public BaseRestResult<String> repayView(O2oRepaymentRecordVo entity) {
		log.debug("工作流访问回款详情：参数billCode：【{}】，nodeAuditorId：【{}】，paymentId：【{}】，referId:【{}】", entity.getBillCode(), entity.getNodeAuditorId(), entity.getPaymentsId(), entity.getReferId());
		String approvalUrl = baseUtils.getApprovalUrl(entity.getNodeAuditorId(), ProcessTemplate.SYSTEM_MODULE_O2O);// 审批代办列表详情URL
		ViewContext.put("approvalUrl", approvalUrl);
		O2oLoanapplyEntity loanEntity = loanService.fingByBillCode(entity.getBillCode());
		if (null == loanEntity) {
			return BaseRestResult.warn("贷款单号异常，请检查数据是否正常");
		}
		O2oRepaymentEntity o2oRepaymentEntity = o2oPaymentsServiceImpl.findEntityById(entity.getReferId());
		O2oPaymentsPlan o2oPaymentsPlan = o2oPaymentsServiceImpl.findByIdEntity(o2oRepaymentEntity.getRepayment_no());
		
		//查询已还款利息金额
		String repayment_interest = o2oPaymentsServiceImpl.findBigDecimal(repayment_interest_sql, o2oRepaymentEntity.getRepayment_no());
		//查询已还款本金金额
		String repayment_penalty = o2oPaymentsServiceImpl.findBigDecimal(repayment_penalty_sql, o2oRepaymentEntity.getRepayment_no());
		
		O2oRepaymentRecordVo entityResouce = new O2oRepaymentRecordVo();
		entityResouce.setBillCode(entity.getBillCode());
		entityResouce.setUserName(o2oPaymentsPlan.getName());
		entityResouce.setPeriods((int) o2oPaymentsPlan.getPeriods());
		entityResouce.setPayPrincipal(o2oPaymentsPlan.getPayPrincipal().toString());
		entityResouce.setPayInterest(o2oPaymentsPlan.getPayInterest().toString());
		entityResouce.setWeiPayPrincipal(o2oPaymentsPlan.getPayPrincipal().subtract(new BigDecimal(repayment_penalty)).toString());
		entityResouce.setWeiPayInterest(o2oPaymentsPlan.getPayInterest().subtract(new BigDecimal(repayment_interest)).toString());
		ViewContext.put("o2oRepaymentEntity", o2oRepaymentEntity);
		ViewContext.put("entity", entityResouce);
		ViewContext.put("loanapply", loanEntity);
		return HtmlRestResult.popHtmlFragment("approval/repayment_approval");
	}

	/**
	 * @Description: <p> 删除还款记录 </p>
	 * @author CXW
	 * @date 2016年9月7日 下午4:19:18
	 * @version V1.0
	 * @param 
	 * @return BaseRestResult<String>
	 */
	@RequestMapping("/deleteRecord")
	public BaseRestResult<String> deleteRepamentRecord(String recordId) {
		String sql = "update o2o_repayment_record orr set orr.is_delete=? where orr.id=? ";
		int i = o2oPaymentsServiceImpl.updateBySQL(sql, "Y" , recordId);
		if (i > 0) {
			return BaseRestResult.info("删除成功").andRefresh();
		} else {
			return BaseRestResult.warn("删除失败，请稍后重试");
		}
	}
	
	/**
	 * @Description: <p> 查看还款详情  </p>
	 * @author CXW
	 * @date 2016年9月7日 下午4:27:04
	 * @version V1.0
	 * @param 
	 * @return BaseRestResult<String>
	 */
	@RequestMapping("/recordView")
	public BaseRestResult<String> recordView(O2oRepaymentRecordVo entity) {
		log.debug("工作流访问回款详情：参数billCode：【{}】，referId:【{}】", entity.getBillCode(), entity.getReferId());
		String approvalUrl = baseUtils.getApprovalAgreeUrl(entity.getReferId(), null, ProcessTemplate.SYSTEM_MODULE_O2O);// 审批代办列表详情URL
		ViewContext.put("approvalUrl", approvalUrl);
		O2oLoanapplyEntity loanEntity = loanService.fingByBillCode(entity.getBillCode());
		if (null == loanEntity) {
			return BaseRestResult.warn("贷款单号异常，请检查数据是否正常");
		}
		O2oRepaymentEntity o2oRepaymentEntity = o2oPaymentsServiceImpl.findEntityById(entity.getReferId());
		O2oPaymentsPlan o2oPaymentsPlan = o2oPaymentsServiceImpl.findByIdEntity(o2oRepaymentEntity.getRepayment_no());
		
		//查询已还款利息金额
		String repayment_interest = o2oPaymentsServiceImpl.findBigDecimal(repayment_interest_sql, o2oRepaymentEntity.getRepayment_no());
		//查询已还款本金金额
		String repayment_principal = o2oPaymentsServiceImpl.findBigDecimal(repayment_penalty_sql, o2oRepaymentEntity.getRepayment_no());
				
		
		O2oRepaymentRecordVo entityResouce = new O2oRepaymentRecordVo();
		entityResouce.setBillCode(entity.getBillCode());
		entityResouce.setUserName(o2oPaymentsPlan.getName());
		entityResouce.setPeriods((int) o2oPaymentsPlan.getPeriods());
		entityResouce.setPayPrincipal(o2oPaymentsPlan.getPayPrincipal().toString());
		entityResouce.setPayInterest(o2oPaymentsPlan.getPayInterest().toString());
		entityResouce.setWeiPayPrincipal(o2oPaymentsPlan.getPayPrincipal().subtract(new BigDecimal(repayment_principal)).toString());
		entityResouce.setWeiPayInterest(o2oPaymentsPlan.getPayInterest().subtract(new BigDecimal(repayment_interest)).toString());
		ViewContext.put("o2oRepaymentEntity", o2oRepaymentEntity);
		ViewContext.put("entity", entityResouce);
		ViewContext.put("loanapply", loanEntity);
		return HtmlRestResult.popHtmlFragment("bank/repayment_detail");
	}
	
	/**
	 * @Description: <p> 查询修改单条还款记录信息  </p>
	 * @author CXW
	 * @date 2016年9月7日 下午4:48:26
	 * @version V1.0
	 * @param 
	 * @return BaseRestResult<String>
	 */
	@RequestMapping("/findRecord")
	public BaseRestResult<String> findRecordById(String recordId){
		O2oRepaymentEntity entity = o2oPaymentsServiceImpl.findRecordById(recordId);
		O2oPaymentsPlan o2oPaymentsPlan = o2oPaymentsServiceImpl.findByIdEntity(entity.getRepayment_no());
		//查询已还款利息金额
		String repayment_interest = o2oPaymentsServiceImpl.findBigDecimal(repayment_interest_sql, entity.getRepayment_no());
		//查询已还款本金金额
		String repayment_penalty = o2oPaymentsServiceImpl.findBigDecimal(repayment_penalty_sql, entity.getRepayment_no());
			
		
		O2oRepaymentRecordVo entityResouce = new O2oRepaymentRecordVo();
		entityResouce.setBillCode(entity.getBill_code());
		entityResouce.setUserName(o2oPaymentsPlan.getName());
		entityResouce.setPeriods((int) entity.getPeriods());
		entityResouce.setPayPrincipal(o2oPaymentsPlan.getPayPrincipal().toString());
		entityResouce.setPayInterest(o2oPaymentsPlan.getPayInterest().toString());
		entityResouce.setWeiPayPrincipal(o2oPaymentsPlan.getPayPrincipal().subtract(new BigDecimal(repayment_penalty)).toString());
		entityResouce.setWeiPayInterest(o2oPaymentsPlan.getPayInterest().subtract(new BigDecimal(repayment_interest)).toString());
		entityResouce.setPaymentsId(recordId);
		ViewContext.put("o2oRepaymentEntity", entity);
		ViewContext.put("entity", entityResouce);
		return HtmlRestResult.popHtmlFragment("bank/repayment");
	}
}
